<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2022-08-15 16:45:26
 * @LastEditors: 李天惊 uf_lee@163.com
 * @LastEditTime: 2023-01-09 10:02:34
 * @FilePath: \grazlink20\uc_sys\src\views\Asset\Quarantine\Index.vue
 * Copyright (c) 2022 by 李天惊 uf_lee@163.com, All Rights Reserved. 
 * 检验检疫记录单
-->
<script setup lang="ts">
import { reactive, PropType, watch, ref, unref } from 'vue'
import { ElButton, ElMessageBox, FormInstance } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
// import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { Table } from '@/components/Table'
import See from './components/See.vue'
import Add from './components/Add.vue'
import Edit from './components/Edit.vue'
import {
  ucIpOwnerListApi,
  ucIpOwnerDelApi,
  ucIpOwnerAddApi,
  ucIpOwnerEditApi
} from '@/api/cy/Guanxi'
import { sysDictRelsApi } from '@/api/dict'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useTable } from '@/hooks/web/useTableTest'
import { useIcon } from '@/hooks/web/useIcon'

const dictRelsData = ref() // 联动数据

// const searchRef = ref() // 搜索的标签
const iconSee = useIcon({ icon: 'ep:view' })
const iconEdit = useIcon({ icon: 'ep:edit' })
const iconDel = useIcon({ icon: 'ep:delete' })

const saveLoading = ref(false) //保存中的状态
const editRef = ref()

// 获取字典
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')
// 字典通过value获取label
const getDictLabel = (type, value) => {
  let data = dict[type].find((item) => {
    return item.value == value
  })
  return data ? data.label : ''
}

// 获取联动关系
const getDictRels = async () => {
  const res = await sysDictRelsApi({
    p_type: 'breed',
    c_type: 'breed_sub'
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    dictRelsData.value = res.data
  }
}

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  }
})

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: ucIpOwnerListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})
const { getList } = methods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'terminal_type',
    label: '终端类型',
    width: 120,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel('terminal_type', cellValue)
    }
  },
  {
    field: 'province',
    label: '省份',
    width: 150
    // search: {
    //   show: true
    // }
  },
  {
    field: 'city',
    label: '城市',
    width: 150
  },
  {
    field: 'admin_org_name',
    label: '系统管理组织',
    width: 120,
    show: true
  },

  {
    field: 'admin_dept_name',
    label: '系统关系部门',
    width: 150
  },
  {
    field: 'admin_user_name',
    label: '系统管理人员',
    width: 150,
    search: {
      show: false
    }
  },
  {
    field: 'ahb_org_name',
    label: '畜牧局组织',
    width: 150
  },
  {
    field: 'ahb_dept_name',
    label: '畜牧局部门',
    width: 150,
    form: {
      show: false
    }
  },
  {
    field: 'ahb_user_name',
    label: '畜牧局人员',
    width: 120,
    form: {
      show: false
    }
  },
  {
    field: 'action',
    width: 150,
    fixed: 'right',
    label: '操作',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

/****************************** 监听设置固定条件 start ******************************/
const newFixedSearch = ref({})
watch(
  () => props.currentRow,
  (val: any) => {
    if (!val) return
    // 设置固定条件
    newFixedSearch.value = {
      customer_id: val.id
    }
    tableObject.fixedSearch = newFixedSearch.value
  },
  {
    deep: true,
    immediate: true
  }
)
/****************************** 监听设置固定条件 end ******************************/

// 删除
const apiDel = async (id) => {
  let delRes = await ucIpOwnerDelApi({ id })
    .catch(() => {})
    .finally(() => {})
  if (delRes) {
    getList()
  }
}

const dialogVisible = ref(false)

const dialogTitle = ref('')

const actionType = ref('')

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0'
      }
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个关系吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}
// 添加
const AddApi = async () => {
  const edit: any = unref(editRef)
  console.log({ ...edit.data }, 'giao')
  let res = await ucIpOwnerAddApi({ ...edit.data })
    .catch(() => {})
    .finally(() => {})
  console.log(res, 'add')
  if (res) {
    dialogVisible.value = false
    tableObject.currentPage = 1
    getList()
  }
  console.log(edit.data)
}
// 修改
const EditApi = async (data) => {
  // const edit: any = unref(editRef)
  console.log(data, 'data')
  let res = await ucIpOwnerEditApi({
    id: data.id,
    terminal_type: data.terminal_type,
    province: data.province,
    city: data.city,
    ahb_org_id: data.ahb_org_id,
    ahb_dept_id: data.ahb_dept_id,
    ahb_user_id: data.ahb_user_id,
    admin_org_id: data.admin_org_id,
    admin_dept_id: data.admin_dept_id,
    admin_user_id: data.admin_user_id
  })
    .catch(() => {})
    .finally(() => {})
  console.log(res, 'add')
  if (res) {
    dialogVisible.value = false
    tableObject.currentPage = 1
    getList()
  }
  // console.log(edit.data.ahb_org_id)
}

const save = async () => {
  const edit = unref(editRef)
  const submitForm = async (ruleFormRef: FormInstance | undefined, type) => {
    if (!ruleFormRef) return
    await ruleFormRef.validate((valid) => {
      if (valid) {
        if (type == 'add') {
          console.log(edit?.data, '222')
          AddApi()
        } else if (type == 'edit') {
          // console.log(edit?.data, '333')
          EditApi(edit?.data)
        }
      } else {
        console.log('error submit!', valid)
      }
    })
  }
  switch (actionType.value) {
    case 'add':
      submitForm(edit?.ruleFormRef, 'add')
      // })
      break
    case 'edit':
      submitForm(edit?.ruleFormRef, 'edit')
      // })
      break
    default:
      console.log('未知类型')
  }
}

/****************************** 初始化 start ******************************/
const init = async () => {
  // 列表查询
  await getList()
  // 获取关联关系
  await getDictRels()
}
init()
/****************************** 初始化 end ******************************/
</script>

<template>
  <ContentWrap>
    <!-- <Search
      ref="searchRef"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    /> -->

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
      :selection="false"
    >
      <template #action="{ row }">
        <ElButton circle :icon="iconSee" @click="action('see', row)" title="查看" />
        <ElButton
          v-if="row.state != 3"
          circle
          :icon="iconEdit"
          @click="action('edit', row)"
          title="编辑"
        />
        <ElButton
          v-if="row.state != 3"
          circle
          :icon="iconDel"
          @click="action('del', row)"
          title="删除"
        />
        <!-- <ElButton circle :icon="iconAssets" @click="action('assets', row)" title="打标资产" /> -->
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit v-if="actionType == 'edit'" ref="editRef" :id="tableObject.currentRow.id" />

    <Add v-if="actionType == 'add'" ref="editRef" />

    <See v-if="actionType == 'see'" :id="tableObject.currentRow.id" />

    <!-- <Assets
      v-if="actionType == 'assets'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    /> -->

    <template #footer>
      <ElButton
        v-if="actionType == 'add' || actionType == 'edit'"
        type="primary"
        :loading="saveLoading"
        @click="save()"
      >
        保存
      </ElButton>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
</template>
